<script setup>
	import {
		ref
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const btnActive1 = ref(false)
	const btnActive2 = ref(false)

	const userManage = uniCloud.importObject('user-manage')
	const roomManage = uniCloud.importObject('room-manage')

	const openid = ref(getApp().globalData.openid)
	const userInfoData = ref(null)

	onLoad(async () => {
		uni.setStorageSync('qrCodeBase64', '');
		uni.showLoading({
			title: '加载中...',
			mask: true,
		})
		const {
			RetObject,
			RetMessage,
			RetCode
		} = await userManage.getUserInfo(openid.value)
		uni.setStorageSync('userInfo', JSON.stringify(RetObject))
		userInfoData.value = RetObject
		console.log(userInfoData.value, '**********');
		inputNickname.value = RetObject.name
		avatarURL.value = RetObject.avatarURL
		uni.hideLoading()
		getQueryParams()
	})

	function getQueryParams() {
		var options = wx.getLaunchOptionsSync().query;
		console.log('Scan query:', options);

		// 如果你想根据参数做某些事情
		if (options.scene) {
			// 这里可以处理 scene 参数
			console.log('Scene ID:', options.scene);
			joinRoom(options.scene)
		}

		if (options.key) {
			// 处理其他参数
			console.log('Key:', options.key);
		}
	}

	const navbarOptions = {
		iconfont: 'icon-more',
		parentMethod: function() {
			uni.navigateTo({
				url: '../personalCenter/index'
			})
		}
	}

	const inputNickname = ref('')

	function submitNickname(e) {
		if (e.detail.pass && inputNickname.value !== '') {
			userManage.updateUserInfo({
				userID: openid.value,
				name: inputNickname.value
			})
			userInfoData.value = {
				...userInfoData.value,
				name: inputNickname.value
			}
			uni.setStorageSync('userInfo', JSON.stringify(userInfoData.value))
		} else {
			uni.showToast({
				title: '请输入合法有效的昵称!',
				icon: 'error'
			})
			inputNickname.value = JSON.parse(uni.getStorageSync('userInfo')).name
		}
	}
	const avatarURL = ref('')

	async function changeHeadImage({
		detail: {
			avatarUrl
		}
	}) {
		const lastDotIndex = avatarUrl.lastIndexOf('.')
		// 提取最后一个点号之后的部分
		const extension = lastDotIndex === -1 ? '.jpg' : avatarUrl.substring(lastDotIndex)
		const {
			fileID
		} = await uniCloud.uploadFile({
			cloudPath: '/userAvatar/' + openid.value + extension,
			filePath: avatarUrl,
		})
		userManage.updateUserInfo({
			userID: openid.value,
			avatarID: fileID
		})
		userInfoData.value = {
			...userInfoData.value,
			avatarID: fileID,
			avatarURL: avatarUrl,
		}
		uni.setStorageSync('userInfo', JSON.stringify(userInfoData.value))
		avatarURL.value = avatarUrl
		console.log(avatarUrl, 'avatarUrl');
	}

	async function createRoom() {
		const url = '../room/index'
		uni.navigateTo({
			url,
			animationType: 'pop-in',
			animationDuration: 200
		})
	}

	const joinRoomPopup = ref(null)
	const roomCode = ref('')

	function openJoinRoomPopup() {
		roomCode.value = ''
		joinRoomPopup.value.open('center')
	}
	async function joinRoom(roomCode = '') {
		const data = await roomManage.getRoomInfo(roomCode)
		console.log('获取房间信息！', data);
		if (data) {
			const url = `../room/index${roomCode ? `?roomCode=${roomCode}` : ''}`
			uni.navigateTo({
				url,
				animationType: 'pop-in',
				animationDuration: 200
			})
		} else {
			uni.showToast({
				title: '没有找到该房间号!',
				icon: 'error'
			})
		}
	}

	function closeJoinRoomPopup() {
		joinRoomPopup.value.close()
	}

	function confirmJoinRoom() {
		if (roomCode.value == '') return uni.showToast({
			title: '亲,没输房间号哦!',
			icon: 'none'
		})
		joinRoom(roomCode.value)
		joinRoomPopup.value.close()
	}
</script>

<template>
	<navbar v-bind='navbarOptions'></navbar>
	<uni-popup ref="joinRoomPopup" type="center">
		<uni-popup-dialog mode="input" title="加入房间" :maxlength="25" message="成功消息" :duration="2000" :before-close="true"
			v-model="roomCode" placeholder="请输入房间号" @close="closeJoinRoomPopup" @confirm="confirmJoinRoom"></uni-popup-dialog>
	</uni-popup>
	<view class="home-page">
		<!-- 头像 -->
		<view class="head-image-wrapper">
			<button class="head-image-box" open-type="chooseAvatar" @chooseavatar="changeHeadImage">
				<image class="image-circle" style="width: 200rpx;height: 200rpx;" :src="avatarURL" mode="aspectFill"></image>
			</button>
			<view class="icon-wrapper">
				<text class="iconfont icon-xiangji head-image-icon"></text>
			</view>
		</view>
		<!-- 用户名 -->
		<view class="nickname-wrapper">
			<input class="nickname-input" type="nickname" placeholder="请输入昵称" maxlength="20" v-model="inputNickname"
				@nicknamereview="submitNickname" />
		</view>
		<!-- 建议 -->
		<view class="suggestion">建议修改为微信头像昵称</view>
		<!-- 创建房间 -->
		<button :style="{boxShadow: btnActive1 ? 'none' : '6rpx 6rpx 6rpx rgba(0, 0, 0, .1)'}" class="create-room"
			type="default" @touchstart="btnActive1 = true" @touchend="btnActive1 = false" @click="createRoom">创建房间</button>
		<!-- 加入房间 -->
		<button :style="{boxShadow: btnActive2 ? 'none' : '6rpx 6rpx 6rpx rgba(0, 0, 0, .1)'}" class="join-room"
			type="default" @touchstart="btnActive2 = true" @touchend="btnActive2 = false"
			@click="openJoinRoomPopup">加入房间</button>
		<!-- 使用说明 -->
		<view class="instructions">使用说明</view>
		<!-- logo -->
		<view class="logo-wrapper">
			<view class="logo">
				<image style="width: 288rpx; height: 80rpx;" src="@/static/images/logo.png" mode="aspectFill"></image>
			</view>
			<view class="suggestion">本程序仅供消遣，请自觉抵制赌博行为。</view>
			<view class="suggestion">远离赌博，珍爱生活。</view>
		</view>
	</view>
</template>

<style lang="scss">
	.home-page {
		display: flex;
		align-items: center;
		flex-direction: column;
		padding: 40rpx;
		padding-top: 150rpx;

		.head-image-wrapper {
			position: relative;
			filter: drop-shadow(4rpx 6rpx 4rpx rgba(0, 0, 0, 0.3));

			.head-image-box {
				margin: 0;
				padding: 0;
				border-radius: 50%;
				line-height: 1;
			}

			.icon-wrapper {
				background-color: #fff;
				position: absolute;
				bottom: 10rpx;
				right: 10rpx;
				padding: 8rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;

				.head-image-icon {
					font-size: 32rpx;
				}
			}
		}

		.nickname-wrapper {
			text-align: center;
			width: calc(100% - 20rpx);
			margin: 60rpx 0;

			.nickname-input {
				text-align: center;
				padding: 30rpx 0;
				background-color: #fff;
				border-radius: 5px;
				box-shadow: 0 0 2rpx rgba(0, 0, 0, .4);
				font-size: 32rpx;
				font-weight: 500;
			}
		}

		.suggestion {
			font-size: 24rpx;
			color: rgba(0, 0, 0, .4);
			letter-spacing: 2rpx;
		}

		.create-room,
		.join-room {
			width: calc(100% - 20rpx);
			padding: 12rpx 0;
			margin: 160rpx 0 60rpx 0;
			background-color: var(--theme-color);
			color: #fff;
			border-radius: 5px;
		}

		.join-room {
			margin-top: 0;
			color: #333;
			background-color: #fff;
		}

		.instructions {
			font-size: 24rpx;
			letter-spacing: 4rpx;
			color: rgba(0, 0, 0, .6);
			padding-bottom: 4rpx;
			border-bottom: 2rpx solid rgba(0, 0, 0, .6);
		}

		.logo-wrapper {
			position: absolute;
			bottom: 60rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.logo {
				margin-bottom: 25rpx;
			}
		}

	}
</style>